package utils;


import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.apache.commons.lang3.ObjectUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;


public class ItextPdf {
	
	public static final void editPdfTemplate(String templateFile ,String outFile,Map<String,Object> map)
	throws IOException, DocumentException {
		PdfReader reader = new PdfReader(templateFile); // 模版文件目录
		PdfStamper ps = new PdfStamper(reader, new FileOutputStream(outFile)); // 生成的输出流
		BaseFont bf = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
		//BaseFont bf = BaseFont.createFont(fontFile, BaseFont.IDENTITY_H , BaseFont.EMBEDDED);
		AcroFields s =  ps.getAcroFields();
		//Font keyfont = new Font(bf, 10, Font.BOLD);// 设置字体大小
		
			//设置文本域表单的字体
			// 对于模板要显中文的，在此处设置字体比在pdf模板中设置表单字体的好处：
			//1.模板文件的大小不变；2.字体格式满足中文要求
		
		for (String key : map.keySet()) {
			   System.out.println("key= "+ key + " and value= " + map.get(key));
			  
			 
			   s.setFieldProperty(key,"textfont",bf,null);
			   s.setFieldProperty(key,"textsize",10,null);
			   s.setField(key, ObjectUtils.toString(map.get(key)));
		}
		
			ps.setFormFlattening(true); // 这句不能少
			ps.close();
			reader.close();
	}
}
